import 'dart:async';

import 'package:dartx/dartx.dart';
import 'package:flutter/material.dart';
import 'package:flutter_blue_plus/flutter_blue_plus.dart';
import 'package:sgy_flutter/ble/ble_manager.dart';
import 'package:rxdart/rxdart.dart' as rx;

class BleStateView extends StatelessWidget {
  final BleManager? bleManager;
  final Widget Function(bool connected) builder;
  final bool? initialData;

  const BleStateView(
      {super.key,
      required this.bleManager,
      required this.builder,
      this.initialData});

  @override
  Widget build(BuildContext context) {
    return StreamBuilder<bool>(
        initialData: bleManager?.connectionState.value ==
            BluetoothConnectionState.connected,
        stream: bleManager?.connectionState.stream
                .map((e) => e == BluetoothConnectionState.connected) ??
            Stream.value(false),
        builder: (BuildContext context, AsyncSnapshot<bool> snapshot) {
          return builder(snapshot.data == true);
        });
  }
}

class BleStateView2 extends StatefulWidget {
  final BleManager? bleManager;
  final BleManager? rightBleManager;
  final Widget Function(bool leftConnected, bool rightConnected) builder;

  const BleStateView2({
    super.key,
    required this.rightBleManager,
    required this.bleManager,
    required this.builder,
  });

  @override
  State<StatefulWidget> createState() {
    return _BleStateView2State();
  }
}
class _BleStateView2State extends State<BleStateView2>{

  StreamSubscription? _subscription1;
  StreamSubscription? _subscription2;
  bool leftConnected = false;
  bool rightConnected = false;
  @override
  void initState() {
    leftConnected = widget.bleManager?.connectionState.value == BluetoothConnectionState.connected;
    rightConnected = widget.rightBleManager?.connectionState.value == BluetoothConnectionState.connected;
    _subscription1 = widget.bleManager?.connectionState.listen((value){
      setState(() {
        leftConnected = value == BluetoothConnectionState.connected;
      });
    });
    _subscription2 = widget.rightBleManager?.connectionState.listen((value){
      setState(() {
        rightConnected = value == BluetoothConnectionState.connected;
      });
    });
    super.initState();
  }

  @override
  void dispose() {
    _subscription1?.cancel();
    _subscription2?.cancel();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return widget.builder(leftConnected, rightConnected);
  }
}


